package guo.xungengauth.controller;

import com.alibaba.fastjson.TypeReference;
import guo.xungengauth.feign.UserFeign;
import guo.xungengauth.service.WeiboService;
import guo.xungengauth.vo.TokenOthers;
import guo.xungengauth.vo.WeiboToken;
import guo.xungengcommon.utils.R;
import guo.xungengcommon.vo.TokenGetUser;
import guo.xungengcommon.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class wbLogin {

    @Value("${weibo.clientid}")
    private String clientId;
    @Value("${weibo.clientsecret}")
    private String clientSecret;
    @Value("${weibo.granttype}")
    private String grantType;
    @Value("${weibo.redirecturi}")
    private String redirectUrI;

    @Autowired
    WeiboService weiboService;

    @Autowired
    UserFeign userFeign;


    /**
     * 1 第三方weibo登录 成功响应就会返回一个code
     * 2 根据code 换取我们所需的个人信息
     * 3 code换取token以及一些其他东西
     * 4 数据库保存用户信息
     * 5 session整合redis 设置session作用域和名字
     * @param code
     * @return
     */
    @GetMapping("/Oauth2/weibo/success")
    public String loginSuccess(@RequestParam("code") String code,HttpSession session){
        WeiboToken weiboToken = new WeiboToken(clientId,clientSecret,grantType,code,redirectUrI);

        TokenOthers tokenOthers = weiboService.getWBToken(weiboToken);
        TokenGetUser tokenGetUser = new TokenGetUser();
        BeanUtils.copyProperties(tokenOthers,tokenGetUser);

        R r = userFeign.saveUser(tokenGetUser);
        UserVo user = (UserVo) r.getData("user", new TypeReference<UserVo>() {
        });
        System.out.println("auth服务得到登录用户: "+user.toString());

        session.setAttribute("user",user);

        return "redirect:http://main.xungeng.com/index";
//        return "redirect:http://127.0.0.1:40000/index";
    }

    @ResponseBody
    @GetMapping("/fail")
    public String failsss(){
        return "fail";
    }


}
